<template>
  <el-card class="card">
    <div slot="header">
      <span>修改密码</span>
    </div>
    <el-form
    ref="formRef"
      :rules="rules"
      size="small"
      label-width="90px"
      class="form"
      :model="formData"
    >
      <el-form-item label="原密码" prop="oldPassword">
        <el-input v-model="formData.oldPassword"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input type="text" v-model="formData.newPassword"></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="twice">
        <el-input v-model="formData.twice"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-button @click="submit" type="primary">确定</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
// 定义原密码验证函数
const YanzhengIstrue = (rule, value, callback) => {
  if (!value) {
    callback(new Error("原密码不能为空"));
  }
else if(!/^[0-9]{6,18}$/.test(value)){
    callback(new Error('密码必须是6-18位的纯数字'))
  }
  else{
    callback()
  }

};
// 定义新密码验证函数
const passwordIstrue = (rule,value,callback)=>{
  if(!value){
    callback(new Error('新密码不能为空'))
  }
  else if(!/^[0-9]{6,18}$/.test(value)){
    callback(new Error('密码必须是6-18位的纯数字'))
  }
//   else if('formData.oldPassword'==='formData.newPassword'){
//     callback(new Error('11111111333333'))
//   }
  else{
    callback()
  }
}
// 确认新密码
const twiceIstrue = (rule,value,callback)=>{
  if(!value){
    callback(new Error('请再次输入新密码'))
  }
  else if(!/^[0-9]{6,18}$/.test(value)){
    callback(new Error('密码必须是6-18位的纯数字'))
  }
  else{
    callback()
  }
}
// 新密码与原密码不能相同
function same(){
    if('formData.oldPassword'==='formData.newPassword'){
            alert('新密码与原密码不能相同')
    }
}
same()

export default {
  data() {
    return {
      formData: {
        oldPassword: "",
        newPassword: "",
        twice: "",
      },
      // 验证规则
      rules: {
        oldPassword: [
          {validator:YanzhengIstrue,trigger:'blur'}
          ],
        newPassword: [
          {validator:passwordIstrue,trigger:'blur'}
          ],
          twice:[{validator:twiceIstrue,trigger:'blur'}]
      },
    };
  },

  // 方法
  methods:{
    submit(){
     this.$refs.formRef.validate(valid=>{
      console.log('valid',valid);
     })
    },
    reset(){
      this.$refs.formRef.resetFields()
    }
  }
};
</script>

<style lang="scss" scoped>
.form {
  width: 285px;
}
</style>